//
//  GoodDetailViewController.m
//  Scanner
//
//  Created by 米明 on 15/5/14.
//  Copyright (c) 2015年 米明. All rights reserved.
//
/*
 URL：http://182.254.221.46:8081/index/upload
 请求方法：POST
 参数：
 id  (商品id)
 filrStr（图片）
 返回数据:
 如果请求成功，返回文件url
 如果失败，返回-1
 */

#import "GoodDetailViewController.h"
#import "GoodsPhotosCell.h"
#import "MJRefresh.h"
#import "ZYQAssetPickerController.h"
#import "UIImage+Fix.h"
#import "PhotosUploadManager.h"
#import "UIImageView+WebCache.h"
#import "PhotoViewController.h"
#import "PhotosUploadManager.h"
#import "SDImageCache.h"

@interface GoodDetailViewController ()<UIScrollViewDelegate,MJRefreshBaseViewDelegate,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UploadTaskDelegate>
{
    MJRefreshHeaderView * _header;
    
    MJRefreshFooterView * _footer;
    
    BOOL _isHeader;
    BOOL _isFooter;
    BOOL _uploading;
    
    NSInteger _maxIndex;//正在上传的任务数
    

}
@property(nonatomic,strong)NSMutableArray * titles;
@property(nonatomic,strong)NSMutableArray * contents;
@property(nonatomic,strong)Goods * goods;
@property(nonatomic,strong)UIActivityIndicatorView * activityView;
@property(nonatomic,strong)NSMutableArray * donePhotos;//已经上传的图片
@property(nonatomic,strong)NSMutableArray * images;//图片数组

@property(nonatomic,strong)NSMutableArray * photoLocUrls;
@property(nonatomic,strong)NSMutableArray * times;//时间戳
@property(nonatomic,strong)AFHTTPRequestOperation *operation;

@end

@implementation GoodDetailViewController
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
-(void)dealloc{
    [_footer free];
    [_header free];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=self.goodCode;
    [self.view addSubview:self.activityView];
    [self initData];
    [self showUI];
    [self searchGoods];
    [self setupHeader];
    
    // Do any additional setup after loading the view.
}

-(void)rightBarBtnItem{
    if (_photoLocUrls.count>0) {
        //创建任务实例
        for ( int i=0; i<_photoLocUrls.count; i++) {
            UploadTask * upTask=[[UploadTask alloc]initWithPhotoPath:_photoLocUrls[i] goods:self.goods];
            NSString * name = [[_photoLocUrls[i] componentsSeparatedByString:@"/"] lastObject];
            NSInteger number = [[[name componentsSeparatedByString:@"."] firstObject] integerValue];
            upTask.number= number;
            [[PhotosUploadManager manager]addOneTask:upTask];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)initData{
    _donePhotos = [[NSMutableArray alloc]init];
    _photoLocUrls = [[NSMutableArray alloc]init];
    _times =[[NSMutableArray alloc]init];
    _images=[[NSMutableArray alloc]init];
   
}
-(void)showUI{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, ScreenSize.height-Nav_Bar_Height) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [self.view addSubview:_tableView];
}

// 刷新状态变更就会调用
- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state{

    if (!_isHeader&&refreshView==_header) {
        //照相
        _isHeader=YES;
        [self takePhoto];
    }
    if (!_isFooter&&refreshView==_footer) {
        //相册中选
        _isFooter=YES;
        [self openPhotosViewController];
    }
    
}
-(void)takePhoto{
    
    if (_images.count>=5) {
        return;
    }
    
    //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
            picker.delegate = self;
            picker.allowsEditing = YES;//设置可编辑
            picker.sourceType = sourceType;
            [self presentModalViewController:picker animated:YES];//进入照相界面
        }
    //sourceType = UIImagePickerControllerSourceTypeCamera; //照相机
    //sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
    //sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //保存的相片
}
-(int)lastIndex{
    
    if (_photoLocUrls.count<=0) {
        return 0;
    }
    
    NSString * path = [_photoLocUrls lastObject];
    
    NSString * name = [[path componentsSeparatedByString:@"/"] lastObject];
    
    NSInteger index = [[[name componentsSeparatedByString:@"."]firstObject] intValue]%1000;
    
    return (int)index;
}
//照相
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
        _isHeader=NO;
        
        [_header endRefreshing];
        
        UIImage * image=[info objectForKey:UIImagePickerControllerOriginalImage];
        
        CGFloat w=image.size.width;
        
        CGFloat h=image.size.height;
        
        image=[image imageCompressForSize:image targetSize:CGSizeMake(780,((CGFloat)h*780.f/(CGFloat)w))];
        
        [_images addObject:image];
        
        NSString * type;
        
        NSData * data=UIImageJPEGRepresentation(image, 0.5);

        if (data.length>256*1024) {
            
            //NSLog(@"value %f",(float)256*1024/(float)[data length]);
            
            data=UIImageJPEGRepresentation(image, (float)256*1024/(float)[data length]);
        }
        
        type=@"jpg";

        //图片保存的路径
        NSString * DocumentsPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager * fileManager=[NSFileManager defaultManager];
        
        //保存到沙盒
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        
        //保存为jpg
        //  goodId序数
        
        NSString * path=[DocumentsPath stringByAppendingString:[NSString stringWithFormat:@"/%@%03d.%@",self.goods.Id,[self lastIndex]+1+(int)_maxIndex,type]];

        
        [fileManager createFileAtPath:path contents:data attributes:nil];
        
        [data writeToFile:path atomically:YES];
        
        NSLog(@"【照相】 loc url %@",path);
        
        //加入到路径中
        [_photoLocUrls addObject:path];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (_photoLocUrls.count>0) {
                [self creatRightBtnItemWithTitle:@"加入任务"];
            }else{
                self.navigationItem.rightBarButtonItem=nil;
            }
            
            [_tableView reloadData];
        });
    }];
}

//点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"取消");
    _isHeader=NO;
    [_header endRefreshing];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)openPhotosViewController{
    
    _isFooter=NO;
    [_footer endRefreshing];
    
    if (_images.count>=5) {
        [self showAlertViewTitle:@"最多上传5张" message:nil cancelButton:@"知道了" otherButtonTitle:nil];
        return;
    }
    
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 5-_images.count;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups=NO;
    picker.delegate=self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        for (int i=0; i<assets.count; i++) {
            
            ALAsset * asset=assets[i];
            
            UIImage * image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            
            //image=[image fixOrientation];
            
            CGFloat w=image.size.width;
            CGFloat h=image.size.height;
            
            image=[image imageCompressForSize:image targetSize:CGSizeMake(780,((CGFloat)h*780/(CGFloat)w))];
            
            [_images addObject:image];
            
            NSString * type;
            
            NSData * data=UIImageJPEGRepresentation(image, 0.5);
            
            if (data.length>256*1024) {
                
                //NSLog(@"value %f",(float)256*1024/(float)[data length]);
                
                data=UIImageJPEGRepresentation(image, (float)256*1024/(float)[data length]);
            }
            
            type=@"jpg";

            //图片保存的路径
            NSString * DocumentsPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            
            //文件管理器
            NSFileManager * fileManager=[NSFileManager defaultManager];
            
            //保存到沙盒
            [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        
            
            //保存为jpg
            
            NSString * path=[DocumentsPath stringByAppendingString:[NSString stringWithFormat:@"/%@%03d.%@",self.goods.Id,i+1+[self lastIndex]+(int)_maxIndex,type]];
            
            [fileManager createFileAtPath:path contents:data attributes:nil];
            
            [data writeToFile:path atomically:YES];
            
            NSLog(@"【相册】loc url %@",path);
            
            [_photoLocUrls addObject:path];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_photoLocUrls.count>0) {
                    [self creatRightBtnItemWithTitle:@"加入任务"];
                }else{
                    self.navigationItem.rightBarButtonItem=nil;
                }
                [_tableView reloadData];
            });
        }
     
        
    });
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [_header endRefreshing];
    _isHeader=NO;
    [_footer endRefreshing];
    _isFooter=NO;
}

- (void)setupHeader
{
    _header=[MJRefreshHeaderView header];
    _header.delegate=self;
    _header.scrollView=self.tableView;
    
    _footer=[MJRefreshFooterView footer];
    _footer.delegate=self;
    _footer.scrollView=self.tableView;
}


-(NSMutableArray *)contents{
    if(!_contents){
        _contents =[NSMutableArray arrayWithArray:@[@"",@"",@"",@"",@"",@""]];
    }
    return _contents;
}
-(NSMutableArray *)titles{
    if (!_titles) {
        _titles=[NSMutableArray arrayWithArray:@[@"名称",@"类别",@"品牌",@"单位",@"进价",@"售价"]];
    }
    return _titles;
}
-(UIActivityIndicatorView *)activityView{
    if (_activityView==nil) {
        _activityView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityView.center=CGPointMake(ScreenSize.width/2.0, ScreenSize.height/2.0-Nav_Bar_Height);
    }
    return _activityView;
}


#pragma mark - 查询商品

-(void)searchGoods{

    [self.activityView startAnimating];
    
    NSString * url=FIND_GOODS_URL;
    
    NSDictionary * parDict=[NSDictionary dictionaryWithObject:self.goodCode forKey:@"code"];
    
 
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"text/html"];
   
    //NSLog(@"^^^^^ %@",parDict);
    
    [manager GET:url parameters:parDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"data : %@",responseObject);
        
        if ([responseObject[RETURN_RET] intValue]==1) {//查询到

                NSDictionary * dataDict=(NSDictionary *)responseObject[RETURN_DATA];

                [self.goods setValuesForKeysWithDictionary:dataDict];
                
                self.goods.Id=[dataDict objectForKey:@"id"];
            
                NSLog(@"goods Id %@",self.goods.Id);
            
            if (self.goods.Id.length<=0) {
               // [self.navigationController popViewControllerAnimated:YES];
                [self showInfo:@"未查询到"];
            }
            
                _maxIndex = [[CoreDataManager shareManager]maxNumberWithGoodsId:self.goods.Id];
            
                NSLog(@"max index %d",(int)_maxIndex);
            
                [self.contents removeAllObjects];
                
                [self.contents addObject:self.goods.name];
                [self.contents addObject:[NSString stringWithFormat:@"%.2f",self.goods.outMoney]];
                [self.contents addObject:self.goods.Class];
                [self.contents addObject:self.goods.pinpai];
                [self.contents addObject:self.goods.unit];
                [self.contents addObject:[NSString stringWithFormat:@"%.2f",self.goods.inMoney]];
                
                
                NSString * images = dataDict[@"images"];
                
                if (images.length>0) {
                    self.goods.imageArr=[NSMutableArray arrayWithArray:[images componentsSeparatedByString:@","]];
                    //NSLog(@"^^^^^%@",self.goods.imageArr);
                }
            
            for (NSString * url in self.goods.imageArr) {
                NSString * imageUrl = [NSString stringWithFormat:@"%@%@",BASE_URL,url];
                [[SDImageCache sharedImageCache]removeImageForKey:imageUrl fromDisk:YES];
            }
            
            [self.tableView reloadData];
            
            
            
        }else if ([responseObject[RETURN_RET] intValue]==-1){
            //[self showAlertViewTitle:@"该商品已上传!!!!" message:nil cancelButton:@"知道了" otherButtonTitle:nil];
           // [self.navigationController popViewControllerAnimated:YES];
            [self showInfo:@"已上传"];
        }
        else{//未查询到
            //[self.navigationController popViewControllerAnimated:YES];
            //[self showAlertViewTitle:@"未查询到给商品" message:nil cancelButton:@"知道了" otherButtonTitle:nil];
            [self showInfo:@"未查询到"];
        }
        
        [self.activityView stopAnimating];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self showAlertViewTitle:@"服务器异常" message:nil cancelButton:@"知道了" otherButtonTitle:nil];
        
        //NSLog(@"%@",error);
        
        [self.activityView stopAnimating];
    }];
}


-(Goods *)goods{
    if (!_goods) {
        _goods=[[Goods alloc]init];
        self.goods.code=self.goodCode;
    }
    return _goods;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
    if (section==0) {
        return 2;
    }else if (section==1){
        return self.goods.imageArr.count;
    }
    return self.photoLocUrls.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    if (indexPath.section==0) {
        
        static NSString * cellID=@"GoodsCell";
        
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        
        if (!cell) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        }
        
        cell.textLabel.text=[NSString stringWithFormat:@"%@:",self.titles[indexPath.row]];
        cell.detailTextLabel.text=[NSString stringWithFormat:@"%@",[self.contents[indexPath.row] length]==0?@"未知":self.contents[indexPath.row]];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section==1){
        
        static NSString * cellID=@"GoodsPhotosCell";
        
        GoodsPhotosCell * cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        
        if (!cell) {
            cell=[[[NSBundle mainBundle]loadNibNamed:cellID owner:self options:nil]lastObject];
        }
        cell.statusLabel.text=@"已上传";
        
        cell.progressLabel.text=nil;
        
        
        NSString * url=[NSString stringWithFormat:@"%@%@",BASE_URL,self.goods.imageArr[indexPath.row]];
        
        [cell.photoImageView sd_setImageWithURL:[NSURL URLWithString:url]placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            if (image) {
                cell.photoImageView.image= [self cutImage:image size:cell.photoImageView.frame.size];
            }

        }];
        

        return cell;
    }
    else if (indexPath.section==2) {
        
        static NSString * cellID=@"GoodsPhotosCell";
        
        GoodsPhotosCell * cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        
        if (!cell) {
            
            cell=[[[NSBundle mainBundle]loadNibNamed:cellID owner:self options:nil]lastObject];
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
        cell.photoImageView.image=[self cutImage:[UIImage imageWithContentsOfFile:_photoLocUrls[indexPath.row]] size:CGSizeMake(60, 60)];
        cell.progressLabel.text=nil;
        cell.statusLabel.text=nil;
        });
        return cell;
        
    }else{
        return nil;
    }
}
//裁剪图片
- (UIImage *)cutImage:(UIImage*)image size:(CGSize)size
{
    //压缩图片
    CGSize newSize;
    
    CGImageRef imageRef = nil;
    
    if ((image.size.width / image.size.height) < (size.width / size.height)) {
        
        newSize.width = image.size.width;
        
        newSize.height = image.size.width * size.height / size.width;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
        
    } else {
        
        newSize.height = image.size.height;
        
        newSize.width = image.size.height * size.width / size.height;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
        
    }
    
    UIImage * img=[UIImage imageWithCGImage:imageRef];
    
    CGImageRelease(imageRef);
    
    return img;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 40;
    }
    return 70;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PhotoViewController * photoV =[[PhotoViewController alloc]init];

    if(indexPath.section==0){
        return;
    }
    else if (indexPath.section==1){
        photoV.photoUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,self.goods.imageArr[indexPath.row]];
    }
    else{
        
        NSString * photoPath=_photoLocUrls[indexPath.row];
      
        UIImage * image=[UIImage imageWithContentsOfFile:photoPath];
        
        photoV.photo=image;
        
    }
    
    photoV.navigationItem.prompt=self.goods.name;
    
    [photoV removePhoto:^{
        [[PhotosUploadManager manager]deletePhotoWithGoodsId:self.goods.Id uri:self.goods.imageArr[indexPath.row] callBack:^(BOOL succeed) {
            if (succeed) {
                NSLog(@"删除成功");
            }
        }];
        
        [self.goods.imageArr removeObjectAtIndex:indexPath.row];
        [_tableView reloadData];
    }];
    
    self.navigationItem.backBarButtonItem.title=nil;

    [self.navigationController pushViewController:photoV animated:YES];

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 20;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return [NSString stringWithFormat:@"已上传:%d张",(int)self.goods.imageArr.count];
    }
    if(section==2){
        return [NSString stringWithFormat:@"等待上传:%d张",(int)_photoLocUrls.count];
    }
    return @"商品信息";
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        editingStyle=UITableViewCellEditingStyleDelete;

        [[PhotosUploadManager manager]deletePhotoWithGoodsId:self.goods.Id uri:self.goods.imageArr[indexPath.row] callBack:^(BOOL succeed) {
            if (succeed) {
                NSLog(@"删除成功");
            }
        }];
       
        [self.goods.imageArr removeObjectAtIndex:indexPath.row];
        [_tableView reloadData];
  
    }else if (indexPath.section==2){
        [self.images removeObjectAtIndex:indexPath.row];
        NSString * path = self.photoLocUrls[indexPath.row];
        NSFileManager *fileManage = [NSFileManager defaultManager];
        //先判断这个文件夹是否存在，如果不存在则创建，否则不创建
        if ([fileManage fileExistsAtPath:path]) {
            
            if([fileManage removeItemAtPath:path error:nil]){
                NSLog(@"删除 路径 %@",path);
            }
        };

        [self.photoLocUrls removeObjectAtIndex:indexPath.row];
        [_tableView reloadData];
    }
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1||indexPath.section==2) {
        return YES;
    }
    return NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
